﻿using BLL;
using DBUtility;
using Fleck;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using Model;
using System.Net;
using System.Net.NetworkInformation;

namespace UtilityHelper
{
    public class Flecks
    {
        private static volatile Flecks instance = null;
        private WebSocketServer m_server;
        private List<IWebSocketConnection> m_allSockets;
        private IWebSocketConnection m_socket;
        private DateTime m_ZXZT_Time = DateTime.Now;
        public bool m_ZXZT_Status = true;
        private int m_lineNum;
        private Thread m_Thread;

        public string ResultMessage { get; set; }

        public static Flecks GetInstance()
        {
            if (instance == null)
            {
                CONST_DEFINE_WEB_BLL bll = new CONST_DEFINE_WEB_BLL();
                var Infos = bll.GetModelList(" Name='DBAddress'");

                if (Infos.Length > 0)
                {
                    string strIP = string.Format("ws://{0}:{1}", Infos[0].ValueOfName, Infos[0].Code);

                    try
                    {
                        instance = new Flecks();
                       // if (instance.PortInUse(Convert.ToInt32(Infos[0].Code)))
                        instance.m_server = new WebSocketServer(strIP);
                        instance.m_allSockets = new List<IWebSocketConnection>();
                        instance.StartServer();
                    }
                    catch (Exception ex)
                    { 
                    }
                }
            }
            return instance;
        }

        private  bool PortInUse(int port)
        {

            IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] iPEndPoints = iPGlobalProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in iPEndPoints)
            {
                if (endPoint.Port == port)
                {
                    return false;
                }
            }

            return true;

        }

        /// <summary>
        /// 启动端口服务
        /// </summary>
        public void StartServer()
        {
            if (m_server != null)
            {
                m_server.Start(socket =>
                {
                    socket.OnOpen = () =>
                    {
                        //m_socket = socket;
                        m_allSockets.Add(socket);
                    };
                    socket.OnClose = () =>
                    {

                        // m_allSockets.Remove(socket);
                    };
                    socket.OnMessage = message =>
                    {
                        if (message == "ZXZT")
                        {
                            m_ZXZT_Time = DateTime.Now;
                        }
                        // m_allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                    };

                }
                  );
            }
        }

        /// <summary>
        /// 向页面发送消息
        /// </summary>
        public void SendMsg(string str)
        {
            //if (m_socket != null)
            //{
            //    m_socket.Send(str);
            //}
            foreach (var socket in m_allSockets)
            {
                if (socket != null)
                {
                    socket.Send(str);
                }

            }
        }

        #region 获取表头数据
        private DataTable GetTableHeadMsg()
        {
            DataTable dt = new DataTable();
            string sql = string.Format("SELECT STA_ID,STA_NAME FROM  INSPECTION_LINE_INFO WHERE LINE_ID = {0}", m_lineNum);
            DbHelper.GetTable(sql, ref dt);
            return dt;
        }

        private DataTable ReBulidHeadTable()
        {
            DataTable dt = GetTableHeadMsg();

            DataTable dTable = new DataTable();
            dTable.Columns.Add("STA_ID", typeof(int));
            dTable.Columns.Add("STA_NAME", typeof(string));

            int i = 1;
            while (dTable.Rows.Count <= dt.Rows.Count && i < 10)
            {
                DataRow dr = dTable.NewRow();
                foreach (DataRow item in dt.Rows)
                {
                    if (Convert.ToInt32(item["STA_ID"]) == i)
                    {
                        dr["STA_ID"] = item["STA_ID"];
                        dr["STA_NAME"] = item["STA_NAME"];
                        dTable.Rows.Add(dr);
                    }
                }
                i++;

            }

            return dTable;
        }

        #endregion

        #region 获取在线状态的数据

        public void SetZXZTMsg(int lineNum)
        {
            try
            {
                m_lineNum = lineNum;
                m_ZXZT_Time = DateTime.Now;
                m_ZXZT_Status = true;
                if (m_Thread == null)
                {
                    m_Thread = new Thread(() =>
                    {
                        while (m_ZXZT_Status)
                        {
                            SendMsg(DataTableToStr());
                            if (m_ZXZT_Time.AddSeconds(30) < DateTime.Now)
                            {
                                m_ZXZT_Status = false;
                                m_Thread = null;
                            }
                            Thread.Sleep(1000);
                        }

                    });
                    m_Thread.Start();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 获取数据库中的数据
        /// </summary>
        /// <returns>返回DataTable</returns>
        private DataTable GetData()
        {
            DataTable dt = new DataTable();
            string strSql = "select ID,HPHM,HPZL,HPZLDH,JCXH,ISNULL(GWBH,-1) AS GWBH,JCZT_STATUS,JYXM FROM VEHICLE_DISPATCH where JCZT_STATUS = 2 and jcxh is not null order by JCXH ASC";
            strSql = string.Format("SELECT DISTINCT A.JCLSH,A.HPHM,ISNULL(A.JCZT_STATUS,0) AS JCZT_STATUS, A.AJLSH,ISNULL(A.GWBH,0) AS GWBH,A.GXRQ,B.IsSuc,C.IsSuc," +
            "CASE WHEN ISNULL(B.IsSuc,0) = 1 AND ISNULL(C.IsSuc,0) = 0 THEN '是' ELSE '否' END AS IS_LOGIN," +
            "CASE WHEN ISNULL(C.IsSuc,0) = 1 THEN '是' ELSE '否' END AS IS_UPLOAD "
            + "FROM VEHICLE_DISPATCH A"
            + " LEFT JOIN NET_AJ_JK_RESULT B ON B.LWLSH = A.AJLSH AND B.JKName = '18c66'"
            + " LEFT JOIN NET_JK_RESULT C ON C.JCLSH = A.JCLSH AND C.JKID = '18C62'"
            + " WHERE A.JCXH = {0} AND CONVERT(VARCHAR(10),A.GXRQ,120) = CONVERT(VARCHAR(10),GETDATE(),120)"
            + " ORDER BY A.GXRQ DESC", m_lineNum);
            DbHelper.GetTable(strSql, ref dt);
            return dt;
        }


        private DataTable ReDataTable(DataTable dt)
        {

            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("OnLine", typeof(int));

            Dictionary<int, int> dic = new Dictionary<int, int>();
            List<int> list = new List<int>();

            int j = 0;
            int i = 1;
            for (int t = 0; t < dt.Rows.Count; t++)
            {
                dt.Rows[t]["ID"] = i;

                if (Convert.ToInt32(dt.Rows[t]["JCZT_STATUS"]) == 2 && t == 0)
                {
                    dt.Rows[t]["OnLine"] = 1;
                    list.Add(Convert.ToInt32(dt.Rows[t]["GWBH"]));

                }
                else if (Convert.ToInt32(dt.Rows[t]["JCZT_STATUS"]) == 2 && t > 0)
                {
                    if (list.Contains(Convert.ToInt32(dt.Rows[t]["GWBH"])))
                    {
                        dt.Rows[t - 1]["OnLine"] = 0;
                    }
                    dt.Rows[t]["OnLine"] = 1;
                }
                else
                {
                    dt.Rows[t]["OnLine"] = 0;
                }

                i++;
            }

            //foreach (DataRow dr in dt.Rows)
            //{
            //    dr["ID"] = i;

            //    i++;

            //}

            return dt;
        }

        /// <summary>
        /// 判断各个工位的状态
        /// </summary>
        /// <param name="gwbh">工位编号</param>
        /// <param name="status">工位状态</param>
        /// <returns>返回工位状态  0：未检  1：已检 2：在检</returns>
        private int JudeGWStatus(int gwbh, int status)
        {
            int i = 0;
            if (status + 1 == gwbh)
            {
                i = 2;
            }
            else if (status + 1 > gwbh)
            {
                i = 1;
            }
            else
            {
                i = 0;
            }
            return i;

        }



        public class JsonDataEntity
        {
            public string Mark
            {
                get;
                set;
            }

            public Object Msg
            {
                get;
                set;
            }

            public Object HeadMsg
            {
                get;
                set;
            }
        }

        /// <summary>
        /// 把DataTable转换成JSON字符串
        /// </summary>
        /// <returns>返回JSON字符串</returns>
        private string DataTableToStr()
        {
            DataTable dt = GetData();
            dt = ReDataTable(dt);

            DataTable dHead = ReBulidHeadTable();

            JsonDataEntity entity = new JsonDataEntity();
            entity.Mark = "ZXZT";
            entity.Msg = dt;
            entity.HeadMsg = dHead;

            string str = JsonConvert.SerializeObject(entity);

            return str;
        }
        #endregion
    }
}
